package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class IWechatServiceImpl implements IWechatService {
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    @Value("${wechat.qppid}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Override
    public String getOpenid(String code) {
        Map map = new HashMap();
        map.put("appid",appid);
        map.put("secret",appSecret);
        map.put("js_code",code);
        map.put("grant_type","authorization_cod");

        HttpResponse execute = HttpUtil.createRequest(Method.GET, OPENID_URL).
                form(map).execute();
        if (execute.isOk()) {
            String body = execute.body();
            JSONObject entries = JSONUtil.parseObj(body);
            return entries.get("openid").toString();
        }
        return null;
    }


    //获取手机号的方法
    @Override
    public String getPhone(String phoneCode) {

        Map<String,Object> params = new HashMap<>();
        params.put("code",phoneCode);


        HttpResponse response = HttpUtil.createRequest(Method.POST, PHONE_URL+getToken())
                .body(JSONUtil.toJsonStr(params))//JSONUtil.toJsonStr(params)
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);

            String phone = jsonObject.getByPath("phone_info.phoneNumber",String.class);

            return phone;
        }
        return null;


    }
    private String getToken() {  //为了获取手机号

        Map<String,Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",appSecret);
        params.put("grant_type","client_credential");


        HttpResponse response = HttpUtil.createRequest(Method.GET, TOKEN_URL)
                .form(params)
                .execute();
        if (response.isOk()) {
            String body = response.body();

            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject.getStr("access_token");


        }
        return null;

    }
}
